import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRouter } from '@/router/routes'
import { mobileRoutes } from '@/router/mobile-routes'
import { ElMessage } from 'element-plus'
import { isMobile } from '@/util/device'

// 根据设备类型选择路由
const routes = isMobile() ? mobileRoutes : constantRouter

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...constantRouter, ...mobileRoutes], // 同时注册PC和移动端路由
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    }
  },
})

// 全局前置守卫
router.beforeEach(async (to: any, from: any, next) => {
  const token = localStorage.getItem('TOKEN')
  const mobile = isMobile()

  // 设备类型重定向逻辑
  if (to.path === '/') {
    if (mobile) {
      return next('/mobile')
    }
  }

  // 权限检查
  if (to.meta.requiresAuth && !token) {
    ElMessage.warning('还未登录，请先登录！')
    next(mobile ? '/mobile/login' : '/')
  } else {
    next()
  }
})

export default router
